﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using ST.Common.Util.Model;
using System;
using System.Net;

namespace ST.Common.Util.Mvc
{
	/// <summary>
	/// 处理错误，并输出为统一的Json格式
	/// </summary>
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
	public class HandleErrorJsonAttribute : Attribute, IExceptionFilter
	{
		protected readonly ILogger logger;

		public HandleErrorJsonAttribute(ILogger<HandleErrorJsonAttribute> _logger)
		{
			logger = _logger;
		}

		public void OnException(ExceptionContext context)
		{
			string controller = context.RouteData.Values["controller"] as string;
			string action = context.RouteData.Values["action"] as string;

			Exception ex = context.Exception;
			logger.LogError(ex.InnerException ?? ex, "请求(" + controller + "->" + action + ")出错：" + ex.Message);

			if (ex is AuthException)
			{
				context.Result = new JsonResultBase(false, "无权限访问，可能用户未登录或登录已过期", (int)HttpStatusCode.Unauthorized);
			}
			else if (ex is BuzException)
			{
				context.Result = new JsonResultBase(false, ex.Message);
			}
			else if (ex is EntityNotFoundException)
			{
				context.Result = new JsonResultBase(false, ex.Message);
			}
			else if (ex is ArgumentException)
			{
				context.Result = new JsonResultBase(false, ex.Message);
			}
			else
			{
				context.Result = new JsonResultBase(false, "请求出错：" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message), (int)HttpStatusCode.InternalServerError);
			}
			context.ExceptionHandled = true;
		}
	}
}
